package com.ky.pro.java.rpc.core.util.http;

import io.netty.buffer.Unpooled;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;

import java.io.UnsupportedEncodingException;

import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

/**
 * @ClassName ResponseUtil
 * @Description TODO
 * @Date 2021/11/21 22:20
 * @Author kevin
 **/
public class ResponseUtil {

    public static HttpResponse createResponseWithException(Exception e) {

        String body = "{\"status\":\"err\", \"data\": {\"msg\":\"exception thrown: + " + e.getMessage() + "\"}}";
        FullHttpResponse response = null;
        try {
            response = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR,
                    Unpooled.wrappedBuffer(body.getBytes("UTF-8")));
        } catch (UnsupportedEncodingException e2) {
            // won't happen!
        }
        response.headers().set("Content-Type", "application/json");
        response.headers().setInt("Content-Length", response.content().readableBytes());
        return response;
    }

}
